<template>
	<view class="my_order">
		<u-tabs :list="tabList" :activeStyle="{
        color: '#FF943C',
		fontSize:'32rpx',
		fontWeight:'bold'
    }" :inactiveStyle="{
        color: '#000000',
		fontSize:'32rpx',
    }" lineColor="#FF943C" @change="handleTabChange" :current="current"></u-tabs>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered"
			@refresherrefresh="onRefresh" :refresher-threshold="50" @scrolltolower="scrolltolower"
			class="my_order_view">
			<template v-if="dataSouse?.length > 0">
				<orderCard v-for="item in dataSouse" :key="item?.id" :item="item" @handleFinish="handleFinish">
				</orderCard>
			</template>
			<u-empty v-else marginTop="100" text="暂无订单" icon="http://qianxueapplet.suoeryun.com/dd.png"></u-empty>
			<view class="safe_area"></view>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, unref, onMounted, getCurrentInstance, onUnmounted } from 'vue';
	import orderCard from "@/components/orderCard";
	import { qxGoodsOrderList, orderHeader, editAddress } from '@/config/goodStuff.api';
	import { onShow } from '@dcloudio/uni-app';

	const tabList = ref();
	const { proxy } = getCurrentInstance();
	const pagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });
	const params = ref({ orderMainStatus: '', userId: '' });
	const status = ref('loadmore');
	const dataSouse = ref([]);
	const triggered = ref(false);
	const scrollTop = ref(0);
	const current = ref(0);

	onShow(() => {
		// params.value.userId = unref(proxy['vuex_user'])?.id;
		// if (params.value.orderMainStatus === '' || params.value.orderMainStatus === '1') {
		// 	handleFinish();
		// }
	})

	onMounted(async () => {
		params.value.userId = unref(proxy['vuex_user'])?.id;
		handleFinish();
		if (params.value.orderMainStatus !== '' && params.value.orderMainStatus !== '1') {
		}
		// 订单详情-刷新列表
		uni.$on('orderDetails', _ => {
			handleFinish();
		})
		// 修改地址监听
		uni.$on('selectAddress', async (item) => {
			const pages = getCurrentPages();
			const currentRoute = pages[pages.length - 1].route;
			if (currentRoute === 'pages/goodStuff/myOrder') {
				const res = await editAddress({ id: item?.orderId, location: item?.location, locationCode: item?.locationCode, address: item?.address, phoneNumber: item?.phoneNumber, consignee: item?.consignee, freightCharges: item?.freightCharges });
				uni.showToast({
					icon: 'success',
					title: res
				})
				const editData = dataSouse.value?.filter(record => record.id === item?.orderId);
				if (editData?.length > 0) {
					editData[0].izEditAddress = '1';
					console.log(editData, dataSouse.value, 'sdf');
				}
			}
		})
		// 售后成功监听
		uni.$on('afterSale', _ => {
			params.value.orderMainStatus = '5';
			current.value = 5;
			handleFinish();
		})
	})

	onUnmounted(() => {
		// 销毁订单详情监听
		uni.$off('orderDetails')
		// 销毁修改地址监听
		uni.$off('selectAddress');
		// 销毁售后监听
		uni.$off('afterSale');
	})

	/**
	 * tabs 监听
	 */
	function handleTabChange(e) {
		console.log(e, 'e');
		params.value.orderMainStatus = e.status;
		current.value = e.index;
		pagination.pageNo = 1;
		loadHeaderData();
		loadData();
	}

	/**
	 * 加载数据
	 */
	async function loadData() {
		if (pagination.pageNo === 1) {
			dataSouse.value = [];
		}
		status.value = 'loading';
		const res = await qxGoodsOrderList({ ...pagination, ...unref(params) });
		triggered.value = false;
		pagination.total = res?.total;
		dataSouse.value?.push(...res?.records);
		if (unref(dataSouse)?.length < pagination.total) {
			status.value = 'loadmore';
		} else {
			status.value = 'nomore';
		}
	}

	/**
	 * 加载表头数据
	 */
	async function loadHeaderData() {
		// 表头
		const res = await orderHeader({});
		tabList.value = res;
	}

	/**
	 * 滚动到底部操作
	 */
	function scrolltolower() {
		if (unref(dataSouse)?.length < pagination.total && (unref(dataSouse)?.length / pagination.pageSize == pagination.pageNo)) {
			pagination.pageNo++;
			loadData();
		}
	}

	/**
	 * 自定义下拉刷新被触发
	 */
	function onRefresh() {
		triggered.value = true;
		handleFinish();
	}

	/**
	 * 倒计时结束回调
	 */
	function handleFinish() {
		pagination.pageNo = 1;
		setTimeout(_ => {
			loadHeaderData();
			loadData();
		}, 100)
	}
</script>

<style lang="scss" scoped>
	.my_order {
		::v-deep .u-tabs {
			background-color: #fff;

			.u-tabs__wrapper {
				.u-tabs__wrapper__scroll-view-wrapper {
					.u-tabs__wrapper__scroll-view {
						.u-tabs__wrapper__nav {
							.u-tabs__wrapper__nav__item {

								text {
									&:nth-child(2) {
										padding: 0 10rpx;
										line-height: 32rpx;
										position: relative;
										top: -13rpx;
										left: -10rpx;
										background-color: #D54941 !important;
										font-size: 20rpx !important;
									}
								}
							}
						}
					}
				}
			}
		}

		.my_order_view {
			height: calc(100vh - 44px);
		}
	}
</style>